/**
 * The contents of this file are subject to the OpenMRS Public License
 * Version 1.0 (the "License"); you may not use this file except in
 * compliance with the License. You may obtain a copy of the License at
 * http://license.openmrs.org
 *
 * Software distributed under the License is distributed on an "AS IS"
 * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
 * License for the specific language governing rights and limitations
 * under the License.
 *
 * Copyright (C) OpenMRS, LLC.  All Rights Reserved.
 */
package org.openmrs.module.datalogging.handler.event;

import java.util.HashMap;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.openmrs.module.datalogging.enums.EventType;

/**
 *
 */
public class EventHandlerFactory {
	
	private static final Log log = LogFactory.getLog(EventHandlerFactory.class);
	
	private static EventHandlerFactory instance;
	
	private Map<EventType, EventHandler> eventHandlerMapping;
	
	private EventHandlerFactory() {
		registerDefaultHandler();
	}
	
	/**
	 * @return
	 */
	private synchronized static EventHandlerFactory getInstance() {
		if (instance == null)
			instance = new EventHandlerFactory();
		return instance;
	}
	
	private void registerDefaultHandler() {
		if (log.isDebugEnabled())
			log.debug("Registering default handler ...");
		getEventHandlerMapping().put(EventType.EVENT_ENCOUNTER_SAVED, new EncounterEventHandler());
		getEventHandlerMapping().put(EventType.EVENT_OBS_SAVED, new ObsEventHandler());
		getEventHandlerMapping().put(EventType.EVENT_LOGIC_EXECUTED, new LogicEventHandler());
	}
	
	/**
	 * Return the value of the EventHandlerMapping
	 * 
	 * @return the EventHandlerMapping
	 */
	private Map<EventType, EventHandler> getEventHandlerMapping() {
		if (eventHandlerMapping == null)
			eventHandlerMapping = new HashMap<EventType, EventHandler>();
		return eventHandlerMapping;
	}
	
	/**
	 * Register a new handler to create Rule object
	 * 
	 * @param event the event name
	 * @param handler the handler class
	 */
	public static void registerHandler(EventType event, EventHandler handler) {
		getInstance().getEventHandlerMapping().put(event, handler);
	}
	
	/**
	 * Search for a event handler in all registered handler
	 * 
	 * @param event the event name
	 * @return handler of the event or null if no handler is registered for the event
	 */
	public static EventHandler getHandler(EventType event) {
		return getInstance().getEventHandlerMapping().get(event);
	}
	
	/**
	 * Unregister a event handler
	 * 
	 * @param event the event that will be unregistered
	 */
	public static void unregisterHandler(EventType event) {
		getInstance().getEventHandlerMapping().remove(event);
	}
	
}
